package com.yyt.emqxauth.controller;

import com.yyt.emqxauth.config.MockUserConfig;
import com.yyt.emqxauth.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

/**
 * @author yangxin
 * @date 2021/3/30
 */
@RestController
@RequestMapping("/emqx")
public class AuthController {

    protected static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Resource
    private MockUserConfig mockUserConfig;

    @PostMapping("/auth")
    public void auth(String clientid, String username, String password, String ip, HttpServletResponse response) {
        logger.info("开始执行emqx认证逻辑，clientid:【{}】,username: 【{}】,password :【{}】,ip:【{}】", clientid, username, password, ip);
        // 查询所有用户
        List<User> users = mockUserConfig.getUsers();
        // 根据emqx服务器传过来的用户名查询出对应的用户
        Optional<User> optional = users.stream().filter(user -> user.getUsername().equals(username)).findFirst();
        // 无法找到对应的用户名
        if (!optional.isPresent()) {
            response.setStatus(401);
            return;
        }
        User user = optional.get();
        // password不正确
        if (!user.getPassword().equals(password)) {
            response.setStatus(401);
            return;
        }
        // 验证通过
        response.setStatus(200);
    }

}
